package cheqex.update;

import java.util.Calendar;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;

import cheqex.update.controllers.DateController;

public class DateSelector extends JPanel {

	Calendar calendar;
	SpinnerNumberModel monthModel, dateModel, yearModel;
	JSpinner spinner1, spinner2, spinner3;
	JLabel m, d, y;
	
	public DateSelector(){
		calendar = Calendar.getInstance();

        //Add the first label-spinner pair.
        int cmonth = calendar.get(Calendar.MONTH)+1;
        monthModel = new SpinnerNumberModel(cmonth, calendar.JANUARY + 1, 
            							calendar.DECEMBER + 1, 1);
        m = new JLabel("Month: ");
        m.setLabelFor(spinner1);
        
        int cday = calendar.get(Calendar.DAY_OF_MONTH);
        dateModel = new SpinnerNumberModel(cday, 1, 31,1);
        d = new JLabel("Day: ");
        d.setLabelFor(spinner2);
        
        int currentYear = calendar.get(Calendar.YEAR);
        yearModel = new SpinnerNumberModel(currentYear, //initial value
                                       currentYear - 100, //min
                                       currentYear + 100, //max
                                       1);                //step
        y = new JLabel("Year: ");
        y.setLabelFor(spinner3);
        add(m);
	    spinner1 = new JSpinner(monthModel);

	    add(spinner1);
	    add(y);
	    spinner2 = new JSpinner(yearModel);
	    add(spinner2);
	    add(d);

	    spinner3 = new JSpinner(dateModel);
	    add(spinner3);
	    JPanel gPanel = new JPanel();
        add(gPanel);
	}
	
	public java.sql.Date getSelectedDate() {
		Calendar cal = Calendar.getInstance();
		java.sql.Date ret;
		
		int mm = Integer.parseInt(monthModel.getValue().toString())-1;
		int dd = Integer.parseInt(dateModel.getValue().toString());
		int yyyy = Integer.parseInt(yearModel.getValue().toString());
		
		if(DateController.checkError(yyyy, mm, dd)){
			cal.set(Calendar.MONTH, mm);
			cal.set(Calendar.DAY_OF_MONTH, dd);
			cal.set(Calendar.YEAR, yyyy);
			cal.set(Calendar.MILLISECOND, 0);
			cal.set(Calendar.HOUR_OF_DAY, 0);
			cal.set(Calendar.MINUTE, 0);
			cal.set(Calendar.SECOND, 0);
			java.util.Date temp = cal.getTime();
			ret = new java.sql.Date(temp.getTime());
			return ret;
		}else return null;
	}
}
